# coding:utf-8
'''
@version: python3.8
@author: ‘eric‘
@license: Apache Licence
@contact: steinven@qq.com
@software: PyCharm
@file: dbtools.py
@time: 2023/10/1 2:41
'''
import sys
import os.path
from datetime import datetime

import requests

sys.path.append(os.getcwd())


from loguru import logger
if getattr(sys, 'frozen', False):
    BASE_DIR = os.path.dirname(sys.executable)
elif __file__:
    BASE_DIR = os.path.dirname(os.path.dirname(__file__))
logger.debug(f'BASE_DIR:{BASE_DIR}')

import pymongo
from loguru import logger

import configparser

# 创建 ConfigParser 实例
config = configparser.ConfigParser()

# 读取配置文件
config.read(os.path.join(BASE_DIR,'config.ini'),encoding='utf-8')  # 替换为您的配置文件路径

db_host = config.get('db', 'host')
port = config.get('db', 'port')
db_name = config.get('db', 'db_name')
c_name = config.get('db', 'c_name')
username = config.get('db', 'username')
password = config.get('db', 'password')



conn = pymongo.MongoClient(f'mongodb://{username}:{password}@{db_host}:{port}/?authMechanism=DEFAULT')
database = conn[db_name]
collection = database[c_name]
def insert_one(data):

    try:
        data.update({
            'update_time': datetime.now(),
        })
        collection.insert_one(data)
    except:
        logger.exception('')
        logger.error('insert fail%s-%s'%(c_name,data))


def create_task(task_id,status_code,status_desc):
    '''
    0：文件下载成功
    1：文件下载失败
    2：放大成功
    3：放大失败
    4：消息发送成功
    5：消息发送失败
    6：图片违规
    :param task_id:
    :param status_code:
    :param status_desc:
    :return:
    '''
    item = {
        'task_id':task_id,
        'status_code':status_code,
        'status_desc':status_desc,
    }
    insert_one(item)

def update_by_id(task_id,item):
    item.update({
        'update_time': datetime.now()
    })
    # 要更新的字段和值
    update_data = {
        "$set": item,
    }

    # 使用 update_many 方法更新匹配的文档
    result = collection.update_many({"task_id": task_id}, update_data)

    # 检查更新是否成功
    if result.modified_count > 0:
        logger.debug(f"成功更新 {result.modified_count} 条文档")
    else:
        logger.debug("未找到匹配的文档")

def check_pan123_file_exists(file_name):
    '''
    根据文件名检查资源在123是否存在
    :param file_name:
    :return:
    '''
    try:
        u = f'https://vip.123pan.cn/1813016409/realpic/{file_name}'
        headers = {'Range': 'bytes=0-1'}
        response = requests.get(u,headers=headers)
        return response.status_code != 403
    except requests.RequestException:
        return False



def query_pan123_file_name(file_name):
    # 查询ID为"task_id"的文档
    logger.info(f'file_name:{file_name}')

    if not check_pan123_file_exists(file_name):
        return
    logger.info(f"file_name:{file_name}")
    return file_name


if __name__ == '__main__':
    # query_pan123_file_name('oDSSg6_8dZtGsPEQ-4NJTVBwQVxE--dc4abe7d58e83ad1bc4aa44f10e97a9e--2.png-all2.jpg')

    logger.info(check_pan123_file_exists('bigpic--oo2Yw5are4HbOaRw5IhVisJaAmGI--53e342cd51616953bfedc4f9c95bf248.jpg-all2.jpg'))